package com.wdd.libbase.view

import android.view.View
import android.widget.GridView
import android.widget.ListView
import com.wdd.libbase.view.ViewAntiShakeClick.SPACE_TIME
import com.wdd.libbase.view.ViewAntiShakeClick.hash
import com.wdd.libbase.view.ViewAntiShakeClick.lastClickTime


/**
 *
 * @ProjectName:    OwnTool
 * @Package:        com.wdd.libbase.view
 * @ClassName:      ViewClickDelay
 * @Description:     扩张各种布局防抖事件
 * @Author:         王丹丹
 * @CreateDate:     2019/12/21 15:28
 * @UpdateUser:     更新者
 * @UpdateDate:     2019/12/21 15:28
 * @UpdateRemark:   更新说明
 * @Version:        1.0
 */
object ViewAntiShakeClick {
    var hash: Int = 0
    var lastClickTime: Long = 0
    var SPACE_TIME: Long = 3000
}

/**
 * 布局的控件防抖点击
 */
infix fun View.antiShakeClick(clickAction: () -> Unit) {
    this.setOnClickListener {
        if (this.hashCode() != hash) {
            hash = this.hashCode()
            lastClickTime = System.currentTimeMillis()
            clickAction()
        } else {
            val currentTime = System.currentTimeMillis()
            if (currentTime - lastClickTime > SPACE_TIME) {
                lastClickTime = System.currentTimeMillis()
                clickAction()
            }
        }
    }
}

/**
 * listView防抖点击
 */
infix fun ListView.antiShakeItemClick(onItemClick: (view: View, position: Int, id: Long) -> Unit) {
    this.setOnItemClickListener { _, view, position, id ->
        if (view.hashCode() != hash) {
            hash = view.hashCode()
            lastClickTime = System.currentTimeMillis()
            onItemClick(view, position, id)
        } else {
            val currentTime = System.currentTimeMillis()
            if (currentTime - lastClickTime > SPACE_TIME) {
                lastClickTime = System.currentTimeMillis()
                onItemClick(view, position, id)
            }
        }
    }
}

/**
 * gridView防抖点击
 */
infix fun GridView.antiShakeItemClick(onItemClick: (view: View, position: Int, id: Long) -> Unit) {
    this.setOnItemClickListener { _, view, position, id ->
        if (view.hashCode() != hash) {
            hash = view.hashCode()
            lastClickTime = System.currentTimeMillis()
            onItemClick(view, position, id)
        } else {
            val currentTime = System.currentTimeMillis()
            if (currentTime - lastClickTime > SPACE_TIME) {
                lastClickTime = System.currentTimeMillis()
                onItemClick(view, position, id)
            }
        }
    }
}